package com.itheima.search.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.behaviour.feign.ApBehaviourEntryFeign;
import com.itheima.behaviour.pojo.ApBehaviorEntry;
import com.itheima.common.pojo.Result;
import com.itheima.common.util.RequestContext;
import com.itheima.search.dto.SearchDto;
import com.itheima.search.pojo.ApUserSearch;
import com.itheima.search.mapper.ApUserSearchMapper;
import com.itheima.search.service.ApUserSearchService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * APP用户搜索信息表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-09-02
 */
@Service
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService {

    @Autowired
    private ApBehaviourEntryFeign apBehaviourEntryFeign;

    @Autowired
    private ApUserSearchMapper apUserSearchMapper;

    /***
     * 用户搜索的词汇保存
     *  1）获取用户搜索的词
     *  2）表数据
     *         entry_id:App行为实体用户ID
     *         status:状态，0 无效，1 有效
     *  3)增加搜索的词汇
     */
    @Override
    public void saveSearch(SearchDto dto) {
        //1）ApBehaviourEntryFeign查询用户信息（游客【未登录，机器号】、会员【已登录，userid】）
        //Integer userId = RequestContext.getNodeValue("id");
        Result<ApBehaviorEntry> entryResult = apBehaviourEntryFeign.getByEquipmentIdOrUserId(dto.getEquipmentId(), dto.getUserId());
        ApBehaviorEntry entry = entryResult.getData();
        if(entry!=null){
            //2）检查当前用户是否搜索过该词汇（数据库中是否存在）
            QueryWrapper<ApUserSearch> searchQueryWrapper = new QueryWrapper<ApUserSearch>();
            searchQueryWrapper.eq("entry_id",entry.getId());
            searchQueryWrapper.eq("keyword",dto.getKeywords());
            ApUserSearch apUserSearch = apUserSearchMapper.selectOne(searchQueryWrapper);
            if(apUserSearch==null){
                apUserSearch = new ApUserSearch();
                apUserSearch.setEntryId(entry.getId());
                apUserSearch.setKeyword(dto.getKeywords());
                apUserSearch.setStatus(1);
                apUserSearchMapper.insert(apUserSearch);
            }else{
                //3）修改状态
                // 【1】第一次搜索，增加
                // 【2】之前搜索过，已经增加过了，但是被删除了（status=0），修改状态
                apUserSearch.setStatus(1);
                apUserSearchMapper.updateById(apUserSearch);
            }
        }
    }

    /***
     * 删除关键词
     * @param keyword
     */
    @Override
    public void deleteUserSearchWord(String keyword) {
        //1:删除当前指定用户或者指定机器编号的用户
        Integer userId = RequestContext.getNodeValue("id");
        Integer equipmentId = RequestContext.getNodeValue("equipmentId");
        Result<ApBehaviorEntry> entryResult = apBehaviourEntryFeign.getByEquipmentIdOrUserId(userId, equipmentId);
        ApBehaviorEntry entry = entryResult.getData();
        if(entry!=null){
            //2:删除->改状态
            QueryWrapper<ApUserSearch> queryWrapper = new QueryWrapper<ApUserSearch>();
            queryWrapper.eq("entry_id",entry.getId());
            queryWrapper.eq("keyword",keyword);
            ApUserSearch apUserSearch = apUserSearchMapper.selectOne(queryWrapper);
            if(apUserSearch!=null){
                apUserSearch.setStatus(0);
                apUserSearchMapper.updateById(apUserSearch);
            }
        }
    }

    @Override
    public List<ApUserSearch> searchList() {
        //1：确定用户（游客、会员）
        Integer userId = RequestContext.getNodeValue("id");
        Integer equipmentId = RequestContext.getNodeValue("equipmentId");
        Result<ApBehaviorEntry> entryResult = apBehaviourEntryFeign.getByEquipmentIdOrUserId(userId, equipmentId);
        ApBehaviorEntry entry = entryResult.getData();
        if(entry!=null){
           return apUserSearchMapper.searchList(entry.getEntryId());
        }
        return null;
    }
}
